package com.sghd.candy.module.box.service;

import com.sghd.candy.module.bag.service.PlayerBagService;
import com.sghd.candy.module.box.manager.*;
import com.sghd.candy.module.element.service.PlayerElementService;
import com.sghd.candy.module.fight.manager.LevelInfo;
import com.sghd.candy.module.fight.service.LevelInfoService;
import com.sghd.candy.module.player.manager.Player;
import com.sghd.candy.module.player.manager.PlayerManager;
import com.sghd.candy.module.skill.manager.SkillConfig;
import com.sghd.candy.module.skill.service.PlayerSkillService;
import com.sghd.candy.module.skill.service.SkillConfigService;
import com.sghd.common.ramcache.aop.AutoLocked;
import com.sghd.common.ramcache.aop.IsLocked;
import com.sghd.common.utils.math.MathUtils;
import com.sghd.pojo.candy.bag.enums.PropType;
import com.sghd.pojo.candy.box.enums.KeyType;
import com.sghd.pojo.candy.box.vo.BoxKeyVo;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Allen
 * @date 2018/12/25
 */
@Service
public class PlayerBoxService {
    private static final Logger logger = LoggerFactory.getLogger(PlayerBoxService.class);
    @Autowired
    private PlayerManager playerManager;
    @Autowired
    private PlayerBoxManager playerBoxManager;
    @Autowired
    private BoxKeysConfigManager boxKeysConfigManager;
    @Autowired
    private SkillConfigService skillConfigService;
    @Autowired
    private PlayerSkillService playerSkillService;
    @Autowired
    private PlayerBagService playerBagService;
    @Autowired
    private PlayerElementService playerElementService;
    @Autowired
    private LevelInfoService levelInfoService;

    @AutoLocked
    public List<Map> openBox(@IsLocked Player player, KeyType keyType, Integer openCount) {
        PlayerBox playerBox = playerBoxManager.getPlayerBox(player.getPlayerId());
        int keyCount = playerBox.getBoxKeys().getOrDefault(keyType.ordinal(), 0);
        if (keyCount == 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("玩家ID[{}]，宝箱钥匙[{}]不存在", player.getPlayerId(), keyType.getKeyName());
            }
            return null;
        }

        if (keyCount < openCount) {
            if (logger.isDebugEnabled()) {
                logger.debug("玩家ID[{}]，宝箱钥匙[{}]，数量不足！", player.getPlayerId(), keyType.getKeyName());
            }
            return null;
        }

        // 扣除钥匙个数
        playerBoxManager.change(playerBox, keyType, -1 * openCount);

        BoxKeysConfig boxKeysConfig = boxKeysConfigManager.getBoxKeysConfig(keyType.ordinal());

        List<Map> openVoList = new ArrayList<>();

        for (int i = 0; i < openCount; i ++) {
            Map<String, Integer> params = new HashMap<>(1);

            double random = Math.random();
            double min = 0, max = 0;

            for (BoxOpenDrop boxOpenDrop : boxKeysConfig.getBoxOpenDrop()) {
                max = MathUtils.add(max, boxOpenDrop.getOpenRate());
                if (random > min && random <= max) {
                    if (boxOpenDrop instanceof BoxOpenMoney) {
                        int randMoney = ((BoxOpenMoney) boxOpenDrop).getRandomMoney();
                        //更新背包
                        playerBagService.change(player, PropType.MONEY, randMoney);
                        params.put("openMoney", randMoney);
                    } else if (boxOpenDrop instanceof BoxOpenElement) {
                        int elementDianShu = ((BoxOpenElement) boxOpenDrop).getOpenCount();
                        //更新五行点数
                        playerElementService.change(player, elementDianShu);
                        params.put("elementDianShu", elementDianShu);
                    } else if (boxOpenDrop instanceof BoxOpenSkill) {
                        int rarity = ((BoxOpenSkill) boxOpenDrop).getRarity();
                        Set skillSet = skillConfigService.findSkill(rarity);
                        // 随机获取技能库里一个技能
                        SkillConfig skillConfig = (SkillConfig) skillSet.toArray()[RandomUtils.nextInt(0, skillSet.size())];
                        // 玩家是否已有该技能
                        Set ownSet = playerSkillService.getPlayerSkill(player);
                        if (ownSet.contains(skillConfig.getSkillId())) {
                            //更新技能碎片
                            playerSkillService.change(player, skillConfig.getDiscount());
                            params.put("debris", skillConfig.getDiscount());
                        } else {
                            //更新玩家技能库
                            playerSkillService.addSkill(player, skillConfig.getSkillId());
                            params.put("skillId", skillConfig.getSkillId());
                        }
                    }
                    break;
                } else {
                    min = max;
                }
            }
            openVoList.add(params);
        }

        return openVoList;
    }

    public List<Map> openBoxByTeach(@IsLocked Player player, KeyType keyType) {
        // 关卡在1-1才有引导开箱教程
        LevelInfo levelInfo = levelInfoService.getLevelInfo(player);
        boolean flag = (levelInfo.getBigLevelId() == 1 && levelInfo.getLevelId() == 1 &&
                (keyType == KeyType.GOLD || keyType == KeyType.SILVER));


        List<Map> openVoList = new ArrayList<>();

        /*if (flag) {
            int guide = playerManager.loadOther(player.getPlayerId(), PLAYER_GUIDE,0, Integer.class);
            if (guide != GUIDE_OPEN_BOX) {
                flag = false;
            }
        }*/

        if (flag) {
            PlayerBox playerBox = playerBoxManager.getPlayerBox(player.getPlayerId());
            if (playerBox.getBoxKeys().getOrDefault(keyType.ordinal(),0) == 0) {
                if (logger.isDebugEnabled()) {
                    logger.debug("玩家ID[{}]，宝箱钥匙[{}]不存在", player.getPlayerId(), keyType.getKeyName());
                }
                return openVoList;
            }
            // 扣除钥匙个数
            playerBoxManager.change(playerBox, keyType,-1);
            Map<String, Integer> params = new HashMap<>(1);
            if (keyType == KeyType.SILVER) {
                playerSkillService.addSkill(player,10013);
                params.put("skillId", 10013);
                openVoList.add(params);
            } else {
                playerSkillService.addSkill(player,1000);
                params.put("skillId", 1000);
                openVoList.add(params);
            }
        }
        return openVoList;
    }

    public void change(Player player, int keyId, int changeNum) {
        PlayerBox playerBox = playerBoxManager.getPlayerBox(player.getPlayerId());
        playerBoxManager.change(playerBox, KeyType.values()[keyId], changeNum);
    }

    public BoxKeyVo getBoxKeyList(Player player) {
        PlayerBox playerBox = playerBoxManager.getPlayerBox(player.getPlayerId());
        BoxKeyVo boxKeyVo = new BoxKeyVo();
        boxKeyVo.setBoxKeys(playerBox.getBoxKeys());
        return boxKeyVo;
    }
}
